package com.qipay.api.alipay.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.qipay.pay.FourPayService;
import com.qipay.pay.entity.CpPayAlipayWapRequest;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/sig/v1")
public class CpCreateOrderController {
    @Value("${api.response.sign.name}")
    String apiResponseSignName;

    @Value("${api.response.key.name}")
    String apiResponseKeyName;

    @Autowired
    FourPayService fourPayService;

    @RequestMapping(value = "/create/order", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    private String createOrder(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = (Map<String, Object>) request.getAttribute("params");
        String cpSecretId = (String) request.getAttribute("cpSecretId");
        CpPayAlipayWapRequest bean = (CpPayAlipayWapRequest) XmlUtils.mapToBean(
                params, CpPayAlipayWapRequest.class);
        bean.setCpSecretId(cpSecretId);
        Map<String, Object> result = fourPayService.wapPayCreateOrder(bean);
        Assert.notNull(result,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_BUSY, ApiStatusEnum.SERVICE_BUSY.getInfo()));

        //处理返回链接，加上本地域名
        if(ApiStatusEnum.OK.getCode().equals(result.get("status"))){
            String pay_info = result.get("pay_info").toString();
            if(pay_info.indexOf("http")==-1){
                pay_info = request.getRequestURL().toString().split("api")[0]+pay_info;
            }
            result.put("pay_info",pay_info);
        }
        //加入签名
        result = ResultUtils.wrapResult(result,bean);
        result = ResultUtils.signResult(result, cpSecretId,apiResponseSignName, apiResponseKeyName);
        return JSONObject.toJSONString(result);
    }
}
